/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2024-08-18
 * Time: 19:40
 */
class Solution2 {
    public ListNode swapPairs(ListNode head) {
        if(head == null || head.next == null) {
            return head;
        }
        ListNode newHead = new ListNode(0);
        newHead.next = head;
        ListNode pre = newHead;
        ListNode cur = pre.next;
        ListNode cur1 = cur.next;
        ListNode cur2 = cur1.next;
        while(cur != null && cur1 != null) {
            pre.next = cur1;
            cur1.next = cur;
            cur.next = cur2;

            pre = cur;
            cur = cur2;
            if(cur != null ) {
                cur1 = cur.next;
            }

            if(cur1 != null) {
                cur2 = cur1.next;
            }
        }
        return newHead.next;
    }
}

//递归
//class Solution {
//    public ListNode swapPairs(ListNode head) {
//        if(head == null || head.next == null) {
//            return head;
//        }
//
//        ListNode cur = swapPairs(head.next.next);
//        ListNode tmp = head.next;
//        head.next.next = head;
//        head.next = cur;
//        return tmp;
//    }
//}
